package com.bj58.ecdata.dbconnectionpool;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bj58.ecdata.dao.util.JdbcUitl;
import com.mchange.v2.c3p0.DataSources;

class SwapConnectionPool extends ConnectionPool
{
	private static final Logger logger = LoggerFactory.getLogger(SwapConnectionPool.class);
	private DataSource datasource;
    public SwapConnectionPool(DataSource datasource)
    {
        this.datasource = datasource;
        registerExitEvent();
    }

    public int GetAllCount()
    {
        return -1;
    }

    public int GetFreeConnCount()
    {
        return -1;
    }

    @Override
    public synchronized Connection Get()
        throws Exception
    {
        return datasource.getConnection();
    }

    @Override
    public synchronized void Release(Connection connection)
    {
        JdbcUitl.closeConnection(connection);
    }

    @Override
    public Connection GetReadConnection()
        throws Exception
    {
        return datasource.getConnection();
    }
   
    private void registerExitEvent()
    {
      Runtime.getRuntime().addShutdownHook(new Thread()
      {
        public void run()
        {
        	try {
				DataSources.destroy(datasource);
			} catch (SQLException e) {
				logger.error("error occurs when destroy datasource!...", e);
			}
        }
      });
    }  
}
